﻿using System;
using System.Collections.Generic;
using UnityEngine;

namespace Space3D
{
    public class AABB : IEquatable<AABB>
    {
        public Vector3 Min { get; set; }
        public Vector3 Max { get; set; }

        public AABB()
        {
            Min = Vector3.zero;
            Max = Vector3.zero;
        }
        public AABB(Vector3 min, Vector3 max)
        {
            Min = min;
            Max = max;
        }

        public void RefreshAABB(Vector3 min, Vector3 max)
        {
            Min = min;
            Max = max;
        }

        public bool IntersectsAABB(AABB box)
        {
            bool xIntersects = (Max.x > box.Min.x) && (Min.x < box.Max.x);
            bool yIntersects = (Max.y > box.Min.y) && (Min.y < box.Max.y);
            bool zIntersects = (Max.z > box.Min.z) && (Min.z < box.Max.z);
            return xIntersects && yIntersects && zIntersects;
        }
        public bool IntersectsAABB2D(AABB box)
        {
            bool xIntersects = (Max.x > box.Min.x) && (Min.x < box.Max.x);
            bool yIntersects = (Max.y > box.Min.y) && (Min.y < box.Max.y);
            return xIntersects && yIntersects;
        }

        public bool Equals(AABB other)
        {
            return Min == other.Min && Max == other.Max;
        }

        public void ExpandBy(AABB b)
        {
            Vector3 min = Min;
            Vector3 max = Max;
            if (b.Min.x < Min.x) { min.x = b.Min.x; }
            if (b.Min.y < Min.y) { min.y = b.Min.y; }
            if (b.Min.z < Min.z) { min.z = b.Min.z; }
            if (b.Max.x > Max.x) { max.x = b.Max.x; }
            if (b.Max.y > Max.y) { max.y = b.Max.y; }
            if (b.Max.z > Max.z) { max.z = b.Max.z; }
            Min = min;
            Max = max;
        }
        public List<Vector2> AABB2Points()
        {
            List<Vector2> points = new List<Vector2>() { new Vector2(Min.x, Max.y), new Vector2(Max.x, Max.y), new Vector2(Max.x, Min.y), new Vector2(Min.x, Min.y) };
            return points;
        }
    }
}